package com.lingkang.flychat.ui.activity.main;

import android.os.Bundle;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.ui.AppBarConfiguration;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.navigation.NavigationView;
import com.lingkang.flychat.R;
import com.lingkang.flychat.config.UrlConfig;
import com.lingkang.flychat.entity.User;
import com.lingkang.flychat.ui.activity.base.BaseActivity;
import com.lingkang.flychat.ui.home.FragmentContacts;
import com.lingkang.flychat.ui.home.FragmentDynamic;
import com.lingkang.flychat.ui.home.FragmentMsg;
import com.orhanobut.hawk.Hawk;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class MainActivity extends BaseActivity {

    public static WebSocket webSocketClient;
    @BindView(R.id.iv_bar_img)
    ImageView ivBarImg;
    @BindView(R.id.tv_bar_title)
    TextView tvBarTitle;
    @BindView(R.id.nav_view)
    NavigationView navView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    //    @BindView(R.id.iv_header_main_img)
    private ImageView ivHeaderMainImg;
    //    @BindView(R.id.tv_header_main_name)
    private TextView tvHeaderMainName;
    //    @BindView(R.id.tv_header_main_autograph)
    private TextView tvHeaderMainAutograph;

    private AppBarConfiguration mAppBarConfiguration;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private List<Fragment> fragmentList = new ArrayList<>();
    private int fragmentPosition = 0;

    public static User info = new User();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initMenu();
        initBottomNavigation();
        initView();
        //初始化好友列表
        MainActivityInit.initFriend();
        initWebsocket();
    }

    private void initView() {
        info = Hawk.get("info");
        LogUtils.d(info.toString());

        //左上角头像
        Glide.with(this)
                .load(info.getImg())
                .apply(RequestOptions.bitmapTransform(new CircleCrop())) //图片圆形
                .into(ivBarImg);
        //从父控件一层一层获取
        ivHeaderMainImg = navView.getHeaderView(0).findViewById(R.id.iv_header_main_img);
        tvHeaderMainName = navView.getHeaderView(0).findViewById(R.id.tv_header_main_name);
        tvHeaderMainAutograph = navView.getHeaderView(0).findViewById(R.id.tv_header_main_autograph);
        // NavigationView中的头像
        Glide.with(this)
                .load(info.getImg())
                .into(ivHeaderMainImg);
        tvHeaderMainName.setText(info.getName());
        tvHeaderMainAutograph.setText(info.getAutograph());


        ivBarImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(navView);
            }
        });
    }

    private void initWebsocket() {
        //MainActivityWebSocket.initWebSocket(this, handler);
        new Thread(new Runnable() {
            @Override
            public void run() {
                WebsocketApp websocketApp = new WebsocketApp();
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(UrlConfig.ws + "?" + Hawk.get("token"))
                        .build();
                client.newWebSocket(request, websocketApp);
                client.dispatcher().executorService().shutdown();
            }
        }).start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void initFragment() {
        //获取管理者
        fragmentManager = getSupportFragmentManager();
        //开启事务
        fragmentTransaction = fragmentManager.beginTransaction();

        fragmentList.add(new FragmentMsg());
        fragmentList.add(new FragmentContacts());
        fragmentList.add(new FragmentDynamic());

        fragmentTransaction.add(R.id.content_home, fragmentList.get(0)).commit();
    }


    private void initBottomNavigation() {
        initFragment();

        BottomNavigationBar bottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
        bottomNavigationBar
                .setActiveColor(R.color.colorBlue)
                .addItem(new BottomNavigationItem(R.mipmap.ic_bar_msg, "消息"))
                .addItem(new BottomNavigationItem(R.mipmap.ic_bar_contacts, "好友"))
                .addItem(new BottomNavigationItem(R.mipmap.ic_bar_dynamic, "动态"))
                .setFirstSelectedPosition(0)
                .initialise();


        bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                if (position == 1) {
                    if (Hawk.get("initFriendList") == null && !(boolean) Hawk.get("initFriendList")) {
                        ToastUtils.showShort("好友列表未初始化完成，请等待");
                        return;
                    }
                }
                //LogUtils.e(position);
                //获取管理者
                fragmentManager = getSupportFragmentManager();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.hide(fragmentList.get(fragmentPosition)).commit();
                fragmentTransaction = fragmentManager.beginTransaction();
                if (fragmentList.get(position).isAdded())
                    fragmentTransaction.show(fragmentList.get(position)).commit();
                else
                    fragmentTransaction.add(R.id.content_home, fragmentList.get(position)).commit();
                fragmentPosition = position;
                switch (position) {
                    case 0:
                        tvBarTitle.setText("消息");
                        break;
                    case 1:
                        tvBarTitle.setText("联系人");
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });
    }

    private void initMenu() {
        //DrawerLayout drawer = findViewById(R.id.drawer_layout);
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
                .setDrawerLayout(drawerLayout)
                .build();
        // drawerLayout.openDrawer(navView);
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(false);
//        super.onBackPressed(); //注释super,拦截返回键功能
    }

    @Override
    protected void onDestroy() {
        //取消监听
//        RxBus.getInstance().unSubcribe();
        super.onDestroy();
    }

    public static WebSocket webSocket;
    public static int num = 0;
    private static int re = 3;

    class WebsocketApp extends WebSocketListener {

        @Override
        public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
            super.onClosing(webSocket, code, reason);
            retry();
        }

        @Override
        public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
            super.onFailure(webSocket, t, response);
            retry();
        }

        @Override
        public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
            LogUtils.i(text);
            super.onMessage(webSocket, text);
        }

        @Override
        public void onOpen(@NotNull WebSocket w, @NotNull Response response) {
            super.onOpen(w, response);
            webSocket = w;
            re = 2;//初始化重连等待
        }

        private synchronized void retry() {
            try {
                Thread.sleep(1000 * (2 << re));
                if (re == 3)
                    re = 2;
                else
                    ++re;
            } catch (InterruptedException e) {
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    WebsocketApp websocketApp = new WebsocketApp();
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(UrlConfig.ws + "?" + Hawk.get("token"))
                            .build();
                    client.newWebSocket(request, websocketApp);
                    client.dispatcher().executorService().shutdown();
                    ++num;
                    Message message = new Message();
                    message.what = 12;
                    message.obj = "重连..." + num;
                    handler.sendMessage(message);
                    LogUtils.d("重连..." + num);
                }
            }).start();
        }
    }
}
